package platformlog_logic

import (
	"context"
	"fmt"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryClusterInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryClusterInfoLogic 查询集群信息
func NewQueryClusterInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryClusterInfoLogic {
	return &QueryClusterInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryClusterInfoLogic) QueryClusterInfo(req *types.QueryClusterInfoRequest) (resp *types.ClusterInfoResponse, err error) {
	var tableName string
	if l.svcCtx.Config.UseMysql {
		tableName = l.svcCtx.Config.Mysql.Tables.ClusterInfo
	} else {
		tableName = l.svcCtx.Config.SQLite.Tables.ClusterInfo
	}

	var querySQL string
	var args []interface{}

	if req.ClusterID == "*" {
		// 查询所有集群信息
		querySQL = fmt.Sprintf(`SELECT id, cluster_id, cluster_name, node_count, cluster_version, created_at, updated_at, status, description, owner, region FROM %s`, tableName)
	} else {
		// 查询特定集群信息
		querySQL = fmt.Sprintf(`SELECT id, cluster_id, cluster_name, node_count, cluster_version, created_at, updated_at, status, description, owner, region FROM %s WHERE cluster_id = ?`, tableName)
		args = append(args, req.ClusterID)
	}

	var clusterInfos []types.ClusterInfo

	err = l.svcCtx.Conn.QueryRows(&clusterInfos, querySQL, args...)
	if err != nil {
		return &types.ClusterInfoResponse{
			Code:    500,
			Message: fmt.Sprintf("查询集群信息失败: %v", err),
		}, err
	}

	if len(clusterInfos) == 0 {
		return &types.ClusterInfoResponse{
			Code:    500,
			Message: "未找到集群信息",
		}, nil
	}

	return &types.ClusterInfoResponse{
		Code:    200,
		Message: "查询集群信息成功",
		Data:    clusterInfos,
	}, nil
}
